package com.czy.owner.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.czy.owner.R;
import com.czy.owner.db.UserHelper;
import com.czy.owner.utils.MyLog;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Created by wangyang on 2016/10/13 0013.
 */
public class AppGuideActivity extends BaseActivity {
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.linear)
    LinearLayout li;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.img_guide)
    ImageView imgGuideStart;
    private int[] images = {R.mipmap.guide_one, R.mipmap.guide_two, R.mipmap.guide_three};
    private List<ImageView> imageViews;//用来存放几个imageview的实例
    private ImageView red_Iv;
    private int left;
    private RxPermissions rxPermissions;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_app_guide;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        rxPermissions = new RxPermissions(AppGuideActivity.this);
        getPermissions();
        viewPager.setAdapter(new MyAdapter());
        imageViews = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(images[i]);
            imageViews.add(imageView);
            ImageView gray_Iv = new ImageView(this);
            gray_Iv.setImageResource(R.mipmap.common_dot_normal);
            //使用LayoutParams改变控件的位置
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
            if (i > 0) {
                layoutParams.leftMargin = 20;
            }
            gray_Iv.setLayoutParams(layoutParams);
            li.addView(gray_Iv);
        }


        red_Iv = new ImageView(this);
        red_Iv.setImageResource(R.mipmap.common_dot_select);
        rl.addView(red_Iv);

        //示图树
        red_Iv.getViewTreeObserver().
                addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    //该方法就是在界面全面绘制结束之后回调
                    @Override
                    public void onGlobalLayout() {
                        // TODO Auto-generated method stub
                        //求距离
                        left = li.getChildAt(1).getLeft() - li.getChildAt(0).getLeft();
                        red_Iv.getViewTreeObserver().removeOnGlobalLayoutListener(this);//
                    }
                });

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                if (position == images.length - 1) {
                    imgGuideStart.setVisibility(View.VISIBLE);
                } else {
                    imgGuideStart.setVisibility(View.GONE);
                }

            }

            //滑动的时候
            @Override
            public void onPageScrolled(int position, float posionOffset, int arg2) {
                // TODO Auto-generated method stub
                RelativeLayout.LayoutParams layoutParams =
                        (RelativeLayout.LayoutParams) red_Iv.getLayoutParams();
                layoutParams.leftMargin = (int) (left * posionOffset + position * left);
                red_Iv.setLayoutParams(layoutParams);
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
//                switch (arg0) {
//                    case ViewPager.SCROLL_STATE_DRAGGING:
//                        flag = false;
//                        break;
//                    case ViewPager.SCROLL_STATE_SETTLING:
//                        flag = true;
//                        break;
//                    case ViewPager.SCROLL_STATE_IDLE:
//                        if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1 && !flag) {
//                            startActivity(new Intent(AppGuideActivity.this, AccountLoginFragment.class));
//                            finish();
//                        }
//                        flag = true;
//                        break;
//                }

            }
        });
    }

    @Override
    protected void updateViews() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //         去掉窗口标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏,全屏显示
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        super.onCreate(savedInstanceState);

    }

    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return images.length;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub

            container.addView(imageViews.get(position));
            return imageViews.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView((View) object);
        }
    }

    @OnClick(R.id.img_guide)
    public void setImgGuideStartOnClick(View view) {
        if (UserHelper.getInstance().isLogined()) {
            MessageHelper.getInstance().reset();
            MyLog.d("King", UserHelper.getInstance().getUserInfoModel(this).getImKey() + "|" + UserHelper.getInstance().getUserInfoModel(this).getImPasswd());
            EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(this).getImKey(), UserHelper.getInstance().getUserInfoModel(this).getImPasswd(), new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getNickName(),
                            UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getUserLogo());

                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();

                    MyLog.d("King", "登录聊天服务器成功！" + UserHelper.getInstance().getUserInfoModel(AppGuideActivity.this).getImKey() + "|" + UserHelper.getInstance().getUserInfoModel(AppGuideActivity.this).getImPasswd());
                    startActivity(new Intent(AppGuideActivity.this, MainActivity.class));
                    finish();
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    MyLog.d("King", "登录聊天服务器失败！" + code + "|" + message);
                    startActivity(new Intent(AppGuideActivity.this, MainActivity.class));
                    finish();
                }
            });
        } else {
            startActivity(new Intent(AppGuideActivity.this, MainActivity.class));
            finish();
        }
    }

    public void getPermissions() {
        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {

                        } else {
                            showMissingPermissionDialog();
                        }
                    }
                });
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少必要权限。\n请点击设置->权限->打开所需权限。");

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }
}

